package com.glp.work.flow.utils;

import com.glp.work.flow.dto.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis Manage
 *
 * @author pengjia
 * @version 2020年8月18日 上午10:16:09
 */
@Component
@Slf4j
public class RedisManage {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Redis 短锁
     *
     * @param rlk
     * @return
     */
    public Boolean defaultLockShortLived(RedisLock rlk) {
        log.info("获取Redis锁：{}", rlk);
        boolean locked = redisTemplate.opsForValue().setIfAbsent(rlk.getKey(), rlk.getValue());
        if (locked) {
            log.info("Redis锁获取成功：{}，设置过期时间为：3秒", rlk);
            redisTemplate.expire(rlk.getKey(), 3, TimeUnit.SECONDS);
        } else {
            log.info("Redis锁获取失败：{}", rlk);
        }
        return locked;
    }


    public void set(String phone, String value) {
        log.info("存入Redis：phone：{}，value:{}", phone, value);
        redisTemplate.opsForValue().set(phone, value, 10, TimeUnit.MINUTES);
    }

    public String get(String phone) {
        log.info("Redis，获取验证码：phone：{}", phone);
        Object o = redisTemplate.opsForValue().get(phone);
        if (o != null) {
            return o.toString();
        }
        return null;
    }


}
